﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AteneoLibriBusinessLogic.Entities;
using AteneoLibri.DomainObject;
using AteneoLibri.Utility;

namespace AteneoLibri.Pages
{
    public partial class Search : System.Web.UI.Page
    {
        User user = null;
        string query = "";

        protected void Page_PreInit(object sender, EventArgs e)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (User.Identity.Name.Equals(System.Configuration.ConfigurationManager.AppSettings["AdminName"]))
                {
                    Page.MasterPageFile = "~/BackEnd/BackEndMasterPage.Master";
                }
                else
                {
                    Page.MasterPageFile = "~/Account/NewAccountMasterPage.Master";
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            user = Utility.HttpSessionManager.GetWebUser();
            
            if (!Page.IsPostBack)
            {
                query = Request.QueryString["q"];

                if (query != null && !query.Equals(""))
                {
                    List<Book> searchResults = SearchBook(query);
                    List<BookInfo> results = new List<BookInfo>();

                    foreach (var item in searchResults)
                    {
                        if (item != null)
                        {
                            BookInfo info = new BookInfo();

                            info.IdBook = item.IdBook;
                            info.Title = item.Title;
                            info.Author = item.Author;
                            info.SellingPrice = item.SellingPrice;
                            info.UserId = item.UserId;

                            using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
                            {
                                User sellerUser = service.getUserById(item.UserId);
                                info.Owner = sellerUser.Username;
                            }

                            results.Add(info);
                        }
                       
                    }

                    pnlNumberOfResults.Visible = true;

                    gvSearchResults.DataSource = results;
                    gvSearchResults.DataBind();

                    gvSearchResultsPortrait.DataSource = results;
                    gvSearchResultsPortrait.DataBind();
                }
                
           }
           else
           {
               var inPageQuery = SearchField.Text.Trim();
               List<Book> findedBooks = SearchBook(inPageQuery);
               List<BookInfo> results = new List<BookInfo>();

               foreach (var item in findedBooks)
               {
                   BookInfo info = new BookInfo();

                   info.IdBook = item.IdBook;
                   info.Title = item.Title;
                   info.Author = item.Author;
                   info.SellingPrice = item.SellingPrice;
                   info.UserId = item.UserId;

                   using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
                   {
                       User sellerUser = service.getUserById(item.UserId);
                       info.Owner = sellerUser.Username;
                   }

                   results.Add(info);
               }

               gvSearchResults.DataSource = results;
               gvSearchResults.DataBind();
           }

            
        }

        private List<Book> SearchBook(string query)
        {
            List<Book> results = new List<Book>();

            using (wsSearch.SearchServiceClient service = new wsSearch.SearchServiceClient())
            {

                results = service.Search(query.ToLower().Trim());

                //results = Utility.Lucene_NET.LuceneFacade.Search(query.ToLower());

                #region OLD SEARCH
                //foreach (var item in books)
                //{
                //    var title = item.Title.ToLower();
                //    var author = item.Author.ToLower();

                //    if (query != null && query != "")
                //    {
                //        if ((title.IndexOf(query.ToLower()) != -1) || (author.IndexOf(query.ToLower()) != -1))
                //        {
                //            results.Add(item);
                //        }
                //    }

                //}
                #endregion

                SearchField.Text = query;
                lblQuery.Text = "\"" + query + "\"";
                lblNumberOfResults.Text = results.Count().ToString();

            }
            Session["BOOK_COLLECTION"] = results;
            return results;
        }

        protected void btnBookDetails_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton button = sender as ImageButton;
            string idBook = button.CommandArgument;

            List<Book> collection = Session["BOOK_COLLECTION"] as List<Book>;
            Response.Redirect("~/BookDetails.aspx?IdBook=" + idBook);
            //Response.Redirect("~/BookDetails.aspx?IdBook=" + idBook + "&fromSearch=1");

        }

        protected void gvSearchResults_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvSearchResults.PageIndex = e.NewPageIndex;
            gvSearchResults.DataBind();
        }

        protected void btnInsertBook_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("~/Account/InsertBook.aspx");
        }

        protected void btnRegistration_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("~/Registration.aspx");
        }

        protected void btnSearchBook_Click(object sender, EventArgs e)
        {
            var inPageQuery = SearchField.Text.Trim();
            //List<Book> findedBooks = SearchBook(inPageQuery);
            //gvSearchResults.DataSource = findedBooks;
            //gvSearchResults.DataBind();
            Response.Redirect("Search.aspx?q=" + inPageQuery);
        }
    }
}